package section

import (
	"context"

	"mall/common/utils/pointy"
	"mall/service/backend/api/internal/logic/utils"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/rpc/backendclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetSectionByIdLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetSectionByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetSectionByIdLogic {
	return &GetSectionByIdLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetSectionByIdLogic) GetSectionById(req *types.IDReq) (*types.SectionInfoResp, error) {
	if req.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	data, err := l.svcCtx.BackendRpc.BackendGetSectionById(l.ctx, &backendclient.IDReq{
		Id: req.Id,
	})
	if err != nil {
		return nil, err
	}

	var media []*types.MediaInfo
	if len(data.Media) > 0 {
		for _, v := range data.Media {
			var url string
			if v.Url != nil && len(*v.Url) > 0 {
				url = *v.Url
			}
			if len(url) == 0 && v.Uri != nil && len(*v.Uri) > 0 {
				url = *v.Uri
			}
			filename, mimeType, metaData := utils.ParseMetaData(v.MetaData)
			media = append(media, &types.MediaInfo{
				Uid:       v.Uid,
				Id:        v.Id,
				Thumbnail: v.Thumbnail,
				Order:     v.Order,
				Url:       pointy.GetPointer(url),
				Name:      pointy.GetPointer(filename),
				MimeType:  pointy.GetPointer(mimeType),
				AltText:   v.AltText,
				MetaData:  pointy.GetPointer(metaData),
			})
		}
	}

	option := utils.GetOptionByStatus(data.Status)

	return &types.SectionInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: &types.SectionInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:         data.Id,
				CreatedAt:  data.CreatedAt,
				UpdatedAt:  data.UpdatedAt,
				DeletedAt:  data.DeletedAt,
				CanAccept:  option.CanAccept,
				CanReject:  option.CanReject,
				CanRemove:  option.CanRemove,
				CanRestore: option.CanRestore,
			},
			Type:      data.Type,
			Title:     data.Title,
			Subtitle:  data.Subtitle,
			PicId:     data.PicId,
			PicUrl:    data.PicUrl,
			Sort:      data.Sort,
			Status:    data.Status,
			StartedAt: data.StartedAt,
			EndedAt:   data.EndedAt,
			Media:     media,
		},
	}, nil
}
